package com.example.template.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Objects;

/**
 * @author BuerYouth
 */
@Slf4j
@Aspect
@Component
public class LoginAop {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Pointcut("execution(* com.example.template.controller..*.*(..))")
    public void logPointCut() {}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        // 遍历接口参数
        for (int i = 0; i < args.length; i++) {
            log.info("第" + (i + 1) + "个参数为:" + args[i]);
        }
        String mthodName = joinPoint.getSignature().getName();
        log.info("需要验证的接口->" + mthodName);
        // 登录接口排除
        String[] bar = {"userLogin", "exit", "uploadFile", "fileDownload", "login"};
        // 转至List查询是否又该排除项
        if (!Arrays.asList(bar).contains(mthodName)) {
            String token = (String)args[1];
            // 判断是否携带有效token
            if (Objects.requireNonNull(stringRedisTemplate.opsForValue().get(token)).isEmpty()) {
                log.error("该Redis键值无效");
                // 没有该键值就报错
                ModelAndView mv = new ModelAndView();
                mv.setViewName("error");
                return mv;
            }
        }
        return joinPoint.proceed();
    }

}